<?php
namespace app\api\job;
use think\Db;
use think\queue\Job;

class Test {

    public function fire(Job $job,$data) {
        // 有些消息在到达消费者时,可能已经不再需要执行了
        $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
        if(!$isJobStillNeedToBeDone){
            $job->delete();
            return;
        }

        $isJobDone = $this->doHelloJob($data);

        if ($isJobDone=='success') {
            // 如果任务执行成功， 记得删除任务
            $job->delete();

//            print("<info>Hello Job has been done and deleted"."</info>\n");
        }else{
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
//                print("<warn>Hello Job has been retried more than 3 times!"."</warn>\n");

                $job->delete();
                // 也可以重新发布这个任务
                //print("<info>Hello Job will be availabe again after 2s."."</info>\n");
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }

    /**
     * 有些消息在到达消费者时,可能已经不再需要执行了
     * @param array|mixed    $data     发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function checkDatabaseToSeeIfJobNeedToBeDone($data){
        return true;
    }
    public static function getMillisecond(){
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectimes = substr($msectime,0,13);
    }

    private function doHelloJob($data)
    {
        echo 1;return true;
        //已有申购抢购
//        $count = Db::name("contract_order")->where(["userid"=>$data['user_id'],"status"=>["in","0,1,2"],"shop_id"=>$data['shop_id']])->count();
//        if($count){
//            return false;
//        }
//        //已有交易中的申购抢购
//        $count = Db::name("contract_process")->where(["sell_userid|buy_userid"=>$data['user_id'],"status"=>["in","0,1"],"shop_id"=>$data['shop_id']])->count();
//        if($count){
//            return false;
//        }
//        //已有商店未到期不能申购抢购
//        $count = Db::name("contract_myshop")->where(["userid"=>$data['user_id'],"status"=>1,"shop_id"=>$data['shop_id']])->count();
//        if($count){
//            return false;
//        }
//        Db::name('contract_order')->insert($data);
//        Db::startTrans();
//        Db::name('session')->where(['id'=>1])->lock(true)->find();
//        //已有抢购
//        $uid=$data['userid'];
//        $result_data=[
//            'userid'=>$uid,
//            'add_time'=>time(),
//            'add_time1'=>$this->getMillisecond(),
//            'order_number'=>$data['order_number'],
//        ];
//        $system_config = system_config();
//        $count = Db::name("contract_order")->where(["type"=>1,"userid"=>$data['userid'],"add_time"=>["between",[getTodayStart(),getTodayEnd()]],"shop_id"=>$data['id']])->count();
//        if($system_config['everyday_open_apply_number'] < $count){
//            $result_data['msg']='超过每日开放数量';
//            $result_data['status']=2;
//            Db::name('contract_order_result')->insert($result_data);
//            Db::commit();
//            return true;

        }
        //已有交易中的抢购
        $count = Db::name("contract_process")->where(["type"=>1,"buy_userid"=>$data['userid'],"add_time"=>["between",[getTodayStart(),getTodayEnd()]],"shop_id"=>$data['id']])->find();
        if($count){
            $result_data['msg']='已有抢购订单';
            $result_data['status']=2;
            Db::name('contract_order_result')->insert($result_data);
            Db::commit();
            return true;
        }
        //已有商店未到期不能申购抢购
//      	$count = Db::name("contract_myshop")->where(["userid"=>$this->userinfo['id'],"status"=>1,"shop_id"=>$id])->lock(true)->find();
//      	if($count){
//            echo returnback(0,lang("已有商店未到期"));exit;
//        }

        //用户抢购开关


        $mid = 109;
        $finance_money = Db::name("finance_money")->where(["id"=>$mid])->find();
        $en_name = $finance_money['en_name'];

        if(Db::name('finance_set')->field('rddburn_way')->where(['id'=>1])->find()['rddburn_way']==1){
            $univalent = coin_usdt(0,$en_name);
        }else{
            if(!empty(Db::name('finance_set')->field('rddburn_num')->where(['id'=>1])->find()['rddburn_num'])){
                $univalent = Db::name('finance_set')->field('rddburn_num')->where(['id'=>1])->find()['rddburn_num'];
            }else{
                $univalent = coin_usdt(0,$en_name);
            }
        }

        //判断是否已有该合约
        $count = Db::name("contract_buy")->where(["userid"=>$uid,"status"=>1,"contract_id"=>$data['id']])->sum("number");
        if(empty($count)){
            $result_data['msg']='请先购买该商品合约';
            $result_data['status']=2;
            Db::name('contract_order_result')->insert($result_data);
            Db::commit();
            return true;
        }
        $contractshop = Db::name("contract_shop")->where(["id"=>$data['id']])->find();
        $contract = Db::name("contract")->where(["id"=>$data['id']])->find();
        //必须大于或等于最小数量
        if($contractshop['end_number'] * $contract['start_percent']/100 > $count * $univalent){
            $result_data['msg']='合约数量已不足';
            $result_data['status']=2;
            Db::name('contract_order_result')->insert($result_data);
            Db::commit();
            return true;
        }



        $buy_userinfo = Db::name("users")->where(["id"=>$uid])->find();
        try{
            //不能直系匹配
            $zong_team = array();
            $zong_team_arr = Db::name("users_invite")->where("repath like '%,".$uid.",%'")->select();
            foreach($zong_team_arr as $k => $v){
                $zong_team[] = $v['userid'];
            }
            $push_team = Db::name("users_invite")->field("GROUP_CONCAT(userid) as alluserid")->where(["re_id"=>$uid])->find()['alluserid'];
            if(!empty($push_team)){
                $push_team = explode(",",$push_team);
                foreach($push_team as $k => $v){
                    $zong_team[] = $v;
                }
            }

            //抢购价格

            $price = mt_rand($contractshop['start_number']*100,$contractshop['end_number']*100)/100;

            $zong_team[] = $uid;
            $sell_order = Db::name("contract_order")->field("*,ABS(".$price." - price) AS new_price")->where(["status"=>1,"type"=>2,"userid"=>["not in",$zong_team]])->order("new_price ASC,sort ASC,id ASC")->find();

            if(empty($sell_order)){
                $result_data['msg']='加油,请继续努力';
                $result_data['status']=2;
                Db::name('contract_order_result')->insert($result_data);
                Db::commit();
                return true;

            }

            if($sell_order['status']!=1 || empty($sell_order['price'])){
                $result_data['msg']='状态错误';
                $result_data['status']=2;
                Db::name('contract_order_result')->insert($result_data);
                Db::commit();
                return true;
            }


            $price = $sell_order['price'];
            if($contractshop['start_number'] > $sell_order['price'] || $contractshop['end_number'] < $sell_order['price']){
                $result_data['msg']='加油,请继续努力';
                $result_data['status']=2;
                Db::name('contract_order_result')->insert($result_data);
                Db::commit();
                return true;
            }



            $system_config = system_config();

            //今天抢购金额

            $money = Db::name("contract_order")->where("type = 1 AND add_time > UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE))")->sum("total_price");
            if($system_config['everyday_open_rob_money'] < $money){
                $result_data['msg']='今天已抢完,明天再来';
                $result_data['status']=2;
                Db::name('contract_order_result')->insert($result_data);
                Db::commit();
                return true;
            }

            //判断是否设置了延期抢购
            if(!empty($sell_order['delay_buy']) && time()<strtotime($sell_order['delay_buy'])){
                $result_data['msg']='抢购未成功，请继续加油';
                $result_data['status']=2;
                Db::name('contract_order_result')->insert($result_data);
                Db::commit();
                return true;
            }
            //今天抢购数量
            $count = Db::name("contract_order")->where("type = 1 AND add_time > UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE))")->count();
            if($system_config['everyday_open_rob_number'] < $count){
                $time = date("Ymd",time());
                $contract_rob_number = Db::name("contract_rob_number")->where(["time"=>$time])->find();
                if(empty($contract_rob_number)){
                    $data1 = array(
                        'time'=>$time,
                        'number'=>1,
                    );
                    Db::name("contract_rob_number")->insert($data1);
                }else{
                    //判断自己是否已经两天没有抢单成功了
                    $day_2_count = Db::name("contract_order")->where("type = 1 AND add_time > UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE) - INTERVAL 2 DAY)")->count();
                    if($day_2_count){
                        $result_data['msg']='今天已抢完,明天再来';
                        $result_data['status']=2;
                        Db::name('contract_order_result')->insert($result_data);
                        Db::commit();
                        return true;
                    }else{
                        if($contract_rob_number['number'] > $system_config['everyday_open_no_rob_number']){
                            $result_data['msg']='今天已抢完,明天再来';
                            $result_data['status']=2;
                            Db::name('contract_order_result')->insert($result_data);
                            Db::commit();
                            return true;
                        }else{
                            Db::name("contract_rob_number")->where(["time"=>$time])->setInc("number");
                        }
                    }
                }
            }



            //如果抢购价格=出售价格  出售订单关闭 否则减去出售订单价格
            if($price == $sell_order['price']){
                $data2 = array(
                    'price'=>0,
                    'status'=>2,
                );
                Db::name("contract_order")->where(["id"=>$sell_order['id']])->update($data2);
            }else{
                $data3 = array(
                    'price'=>$sell_order['price']-$price,
                );
                Db::name("contract_order")->where(["id"=>$sell_order['id']])->update($data3);
            }

            $system_config = system_config();
            $make_overtime = $system_config['contract_make_overtime'];//打款超时时间

            //抢购收益
            $income = $price * $contractshop['total_income_rob'] / 100;

            //插入交易订单
            $data4 = array(
                'buy_id'=>0,
                'sell_id'=>$sell_order['id'],
                'type'=>1,
                'buy_userid'=>$uid,
                'buy_username'=>$buy_userinfo['username'],
                'sell_userid'=>$sell_order['userid'],
                'sell_username'=>$sell_order['username'],
                'price'=>$price,
                'shop_price'=>$price,
                'income'=>$income,
                'shop_id'=>$data['id'],
                'shop_name'=>$contractshop['name'],
                'status'=>0,//0待打款 1待收款 2交易完成 3打款超时 4收款超时 5买家申述 6卖家申述 7交易失败
                'bank'=>$sell_order['bank'],
                'alipay'=>$sell_order['alipay'],
                'weixin'=>$sell_order['weixin'],
                'add_time'=>time(),
                'update_time'=>time(),
                'make_overtime'=>time()+$make_overtime,//打款超时时间
            );
            $process_id = Db::name("contract_process")->insertGetId($data4);


            $sell_userinfo = Db::name("users")->where(["id"=>$sell_order['userid']])->find();


            //给买家发送短信
            action('api/api/sms', ['phone' => $buy_userinfo['tel'],"code"=>"","content" => "【{webname}】您有一个抢购订单，请及时处理！",'num_code' => $buy_userinfo['code']]);

            //给卖家发送短信
            action('api/api/sms', ['phone' => $sell_userinfo['tel'],"code"=>"","content" => "【{webname}】您有一个抢购订单需要确认，请及时处理！",'num_code' => $sell_userinfo['code']]);
            $result_data['msg']='操作成功';
            $result_data['status']=1;
            $result_data['process_id']=$process_id;
            Db::name('contract_order_result')->insert($result_data);
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;

        }


    }
}

